

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>rfml.nn.eval.accuracy &mdash; RFML w/ PyTorch Software Documentation 1.0.0 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../../_static/language_data.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html" class="icon icon-home"> RFML w/ PyTorch Software Documentation
          

          
          </a>

          
            
            
              <div class="version">
                1.0.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../data.html"> Data</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../nbutils.html"> Notebook Utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../nn.html"> Neural Networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../ptradio.html"> PyTorch Radio</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">RFML w/ PyTorch Software Documentation</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
      <li>rfml.nn.eval.accuracy</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for rfml.nn.eval.accuracy</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;Helper function for computing the (top-k) accuracy of a model on a dataset.</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">__author__</span> <span class="o">=</span> <span class="s2">&quot;Bryse Flowers &lt;brysef@vt.edu&gt;&quot;</span>

<span class="c1"># External Includes</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">torch.utils.data</span> <span class="k">import</span> <span class="n">DataLoader</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Tuple</span>

<span class="c1"># Internal Includes</span>
<span class="kn">from</span> <span class="nn">rfml.data</span> <span class="k">import</span> <span class="n">Dataset</span><span class="p">,</span> <span class="n">Encoder</span>
<span class="kn">from</span> <span class="nn">rfml.nn.model</span> <span class="k">import</span> <span class="n">Model</span>


<div class="viewcode-block" id="compute_accuracy"><a class="viewcode-back" href="../../../../nn.html#rfml.nn.eval.accuracy.compute_accuracy">[docs]</a><span class="k">def</span> <span class="nf">compute_accuracy</span><span class="p">(</span>
    <span class="n">model</span><span class="p">:</span> <span class="n">Model</span><span class="p">,</span>
    <span class="n">data</span><span class="p">:</span> <span class="n">Dataset</span><span class="p">,</span>
    <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span><span class="p">,</span>
    <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">512</span><span class="p">,</span>
    <span class="n">mask</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">mask</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">float</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Compute the Top-1 accuracy of this model on the dataset.</span>

<span class="sd">    Args:</span>
<span class="sd">        model (Model): (Trained) model to evaluate.</span>
<span class="sd">        data (Dataset): (Testing) data to use for evaluation.</span>
<span class="sd">        le (Encoder): Mapping from human readable to machine readable.</span>
<span class="sd">        batch_size (int, optional): Defaults to 512.</span>
<span class="sd">        mask (pd.DataFrame.mask, optional): Mask to apply to the data before computing</span>
<span class="sd">                                            accuracy.  Defaults to None.</span>

<span class="sd">    Returns:</span>
<span class="sd">        float: Top-1 Accuracy</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">dl</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span>
        <span class="n">data</span><span class="o">.</span><span class="n">as_torch</span><span class="p">(</span><span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">),</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span>
    <span class="p">)</span>

    <span class="n">right</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">for</span> <span class="n">_</span><span class="p">,</span> <span class="n">data</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">dl</span><span class="p">):</span>
        <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">data</span>
        <span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>
        <span class="n">right</span> <span class="o">+=</span> <span class="p">(</span><span class="n">predictions</span> <span class="o">==</span> <span class="n">labels</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="nb">len</span><span class="p">(</span><span class="n">labels</span><span class="p">)</span>

    <span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">right</span><span class="p">)</span> <span class="o">/</span> <span class="n">total</span></div>


<div class="viewcode-block" id="compute_accuracy_on_cross_sections"><a class="viewcode-back" href="../../../../nn.html#rfml.nn.eval.accuracy.compute_accuracy_on_cross_sections">[docs]</a><span class="k">def</span> <span class="nf">compute_accuracy_on_cross_sections</span><span class="p">(</span>
    <span class="n">model</span><span class="p">:</span> <span class="n">Model</span><span class="p">,</span> <span class="n">data</span><span class="p">:</span> <span class="n">Dataset</span><span class="p">,</span> <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span><span class="p">,</span> <span class="n">column</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">512</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Tuple</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">float</span><span class="p">],</span> <span class="n">List</span><span class="p">]:</span>
    <span class="sd">&quot;&quot;&quot;Compute an accuracy on each unique value in the column (such as SNR or CFO)</span>

<span class="sd">    Args:</span>
<span class="sd">        model (Model): (Trained) model to evaluate.</span>
<span class="sd">        data (Dataset): (Testing) data to use for evaluation.</span>
<span class="sd">        le (Encoder): Mapping from human readable to machine readable.</span>
<span class="sd">        column (str): Name of the column to use for computing cross sections (e.g. SNR)</span>
<span class="sd">        batch_size (int, optional): Defaults to 512.</span>

<span class="sd">    Returns:</span>
<span class="sd">        List[float], List[object]: Accuracy vs Column, Column Values</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">column</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">data</span><span class="o">.</span><span class="n">columns</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
            <span class="s2">&quot;Cannot compute a cross section across the </span><span class="si">{}</span><span class="s2"> column because it does not &quot;</span>
            <span class="s2">&quot;exist in the dataset -- </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">column</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
        <span class="p">)</span>

    <span class="n">accuracy</span> <span class="o">=</span> <span class="nb">list</span><span class="p">()</span>
    <span class="n">column_values</span> <span class="o">=</span> <span class="nb">list</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">data</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">column</span><span class="p">]</span><span class="o">.</span><span class="n">unique</span><span class="p">():</span>
        <span class="n">mask</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">df</span><span class="p">[</span><span class="n">column</span><span class="p">]</span> <span class="o">==</span> <span class="n">val</span>
        <span class="n">column_values</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">val</span><span class="p">)</span>
        <span class="n">accuracy</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
            <span class="n">compute_accuracy</span><span class="p">(</span>
                <span class="n">model</span><span class="o">=</span><span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">data</span><span class="p">,</span> <span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span>
            <span class="p">)</span>
        <span class="p">)</span>

    <span class="k">return</span> <span class="n">accuracy</span><span class="p">,</span> <span class="n">column_values</span></div>


<div class="viewcode-block" id="compute_topk_accuracy"><a class="viewcode-back" href="../../../../nn.html#rfml.nn.eval.accuracy.compute_topk_accuracy">[docs]</a><span class="k">def</span> <span class="nf">compute_topk_accuracy</span><span class="p">(</span>
    <span class="n">model</span><span class="p">:</span> <span class="n">Model</span><span class="p">,</span>
    <span class="n">data</span><span class="p">:</span> <span class="n">Dataset</span><span class="p">,</span>
    <span class="n">le</span><span class="p">:</span> <span class="n">Encoder</span><span class="p">,</span>
    <span class="n">k</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span>
    <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">512</span><span class="p">,</span>
    <span class="n">mask</span><span class="p">:</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="o">.</span><span class="n">mask</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">float</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Computes the probability that the true class is in the top k outputs of the network.</span>

<span class="sd">    .. warning::</span>

<span class="sd">        If you only want Top-1 Accuracy (if you don&#39;t know what this is, then that is what</span>
<span class="sd">        you want).  Then you should just use compute_accuracy instead.</span>

<span class="sd">    Args:</span>
<span class="sd">        model (Model): (Trained) model to evaluate.</span>
<span class="sd">        data (Dataset): (Testing) data to use for evaluation.</span>
<span class="sd">        le (Encoder): Mapping from human readable to machine readable.</span>
<span class="sd">        k (int): Value to use when determining the &quot;top k&quot;.</span>
<span class="sd">        batch_size (int, optional): Defaults to 512.</span>
<span class="sd">        mask (pd.DataFrame.mask, optional): Mask to apply to the data before computing</span>
<span class="sd">                                            top-k accuracy.  Defaults to None.</span>

<span class="sd">    Returns:</span>
<span class="sd">        float: Top-K Accuracy</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">dl</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span>
        <span class="n">data</span><span class="o">.</span><span class="n">as_torch</span><span class="p">(</span><span class="n">le</span><span class="o">=</span><span class="n">le</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">),</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span>
    <span class="p">)</span>

    <span class="n">right</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">for</span> <span class="n">_</span><span class="p">,</span> <span class="n">data</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">dl</span><span class="p">):</span>
        <span class="n">inputs</span><span class="p">,</span> <span class="n">labels</span> <span class="o">=</span> <span class="n">data</span>
        <span class="n">outputs</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">outputs</span><span class="p">(</span><span class="n">inputs</span><span class="p">)</span>

        <span class="c1"># outputs: B x n_classes</span>
        <span class="c1"># Therefore, we retrieve the indices of the top k largest values along dim=1</span>
        <span class="c1"># ---- note: indices/label integers are interchangable nomenclature</span>
        <span class="c1"># topk_predictions: B x k</span>
        <span class="n">topk_predictions</span> <span class="o">=</span> <span class="n">outputs</span><span class="o">.</span><span class="n">topk</span><span class="p">(</span><span class="n">k</span><span class="o">=</span><span class="n">k</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">largest</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span><span class="o">.</span><span class="n">indices</span>

        <span class="c1"># Now, we want to retrieve a 0/1 indicator of whether the true label (for that</span>
        <span class="c1"># specific batch index) is in the top k labels output by the network</span>
        <span class="c1"># labels: B</span>
        <span class="c1"># Therefore, we must add a k dimension to the labels and repeat the true label</span>
        <span class="c1"># across that dimension -- then we can use element wise equality operators</span>
        <span class="c1"># because the sizes will match between topk_predictions and the labels</span>
        <span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>  <span class="c1"># -1 means expand to fit the data</span>
        <span class="c1"># labels: B x 1</span>
        <span class="n">labels</span><span class="o">.</span><span class="n">expand_as</span><span class="p">(</span><span class="n">topk_predictions</span><span class="p">)</span>
        <span class="c1"># Now, the label has been repeated across the second dimension &quot;k times&quot;</span>
        <span class="c1"># labels: B x k</span>
        <span class="c1"># When computing element wise equality, it is only 1 when the labels match,</span>
        <span class="c1"># therefore, the number of correct predictions can simply be a sum of all 1&#39;s</span>
        <span class="c1"># in the return value from the equality</span>
        <span class="n">right</span> <span class="o">+=</span> <span class="p">(</span><span class="n">topk_predictions</span> <span class="o">==</span> <span class="n">labels</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="nb">len</span><span class="p">(</span><span class="n">labels</span><span class="p">)</span>

    <span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">right</span><span class="p">)</span> <span class="o">/</span> <span class="n">total</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2019, Bryse Flowers

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>